package org.example;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.env.BasicIniEnvironment;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

@Slf4j
public class Main {
    public static void main(String[] args) {
        // 创建一个基于INI配置文件的Shiro环境
        BasicIniEnvironment basicIniEnvironment = new BasicIniEnvironment("classpath:shiro.ini");
        // 从环境中获取SecurityManager
        SecurityManager securityManager = basicIniEnvironment.getSecurityManager();
        // 将SecurityManager设置到SecurityUtils，这样整个应用都能使用
        SecurityUtils.setSecurityManager(securityManager);

        // 获取当前的Subject。Subject代表了当前用户
        Subject subject = SecurityUtils.getSubject();

        // 创建用户名密码令牌，这里使用"zhangsan"作为用户名，"z3"作为密码
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("zhangsan", "z3");

        // 执行登录操作
        try {
            subject.login(usernamePasswordToken);

            // 如果没有抛出异常，则登录成功
            System.out.println("登录成功");

            // judge role
            boolean role1 = subject.hasRole("role1");
            System.out.println("has role1=" + role1);

            // judge permission
            boolean permitted = subject.isPermitted("user:insert");
            System.out.println("has user:insert=" + permitted);
            // can also use 'checkPermission', but it has not return value and has not permission
            // to throw AuthenticationException
//            subject.checkPermission("user:insert");

        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("user not exist");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("password error");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("Authentication failed");
        }
    }
}